package com.webserver;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;

public class RequestCAServerCert {
	public static final String CAServerIP = "localhost";
	public static final int CAServerPort = 10001;
	public static final int CAServerFilePort = 10008;
	Socket socket;
	InetAddress serverAddr;
	private ObjectOutputStream oos;
    
	public RequestCAServerCert(){
		try {
			serverAddr = InetAddress.getByName(CAServerIP);
			socket = new Socket(serverAddr, CAServerPort);
			oos = new ObjectOutputStream(socket.getOutputStream());
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public X509Certificate getCAServerCert(){
		X509Certificate caCert = null;
			try {
				oos.writeObject("hello");
				FileReceiveThread frt = new FileReceiveThread(CAServerIP, CAServerFilePort, "CACert.der");
				frt.run();
			} catch (IOException e2) {
				// TODO Auto-generated catch block
				e2.printStackTrace();
			}
		
		/******************** CA server 인증서 불러온다 ****************************/
		
		try {
			FileInputStream fis = new FileInputStream("CACert.der");
			CertificateFactory certificateFactory = CertificateFactory
			.getInstance("X509");
			caCert = (X509Certificate) certificateFactory.generateCertificate(fis);
			fis.close();
			
		} catch (FileNotFoundException e1) {
			e1.printStackTrace();
		} catch (CertificateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		System.out.println("ca received");
		return caCert;
		
	}
}
